package top.braycep.ui;

import top.braycep.utils.FileUtils;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Vector;

public class ButtonEditor extends DefaultCellEditor {
    private JButton button;
    private JPanel panel;
    private MainUI mainUI;

    private JTable table;
    private int row, col;

    public ButtonEditor(MainUI mainUI) {
        super(new JTextField());

        this.mainUI = mainUI;

        setClickCountToStart(1);

        button = new JButton();
        button.setBounds(0, 0, 20, 20);

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                fireEditingStopped();
            }
        });

        panel = new JPanel(null);
        panel.add(button);
    }

    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        this.table = table;
        this.row = row;
        this.col = column;

        button.setText("Editing");
        return panel;
    }

    public Object getCellEditorValue() {
        return button.getText();
    }

    public boolean stopCellEditing() {
        return super.stopCellEditing();
    }

    protected void fireEditingStopped() {
        super.fireEditingStopped();

        File[] files = FileUtils.chooseFiles(mainUI, null);
        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                DefaultTableModel model = (DefaultTableModel) table.getModel();
                Vector dataVector = model.getDataVector();
                if (dataVector.size() < row + i + 1) {
                    model.addRow(new Object[]{null, null, "...", null, null, null, true, null});
                }

                String filePath = files[i] == null ? "" : files[i].getAbsolutePath();
                table.getModel().setValueAt(filePath, row + i, col - 1);

                if (mainUI.getCheckBoxMenuItemAnalysisPath().isSelected()) {
                    String fileUri = FileUtils.analysisPath(filePath);
                    table.getModel().setValueAt(fileUri, row + i, col + 1);
                }
            }
        }
    }
}
